package com.sunday.pinxinghui.model.order;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.squareup.picasso.Picasso;
import com.sunday.common.alipay.PayResult;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.base.Constant;
import com.sunday.pinxinghui.entity.Member;
import com.sunday.pinxinghui.entity.OrderCreate;
import com.sunday.pinxinghui.entity.PrePay;
import com.sunday.pinxinghui.model.account.PurseActivity;
import com.sunday.pinxinghui.model.account.RechargeActivity;
import com.sunday.pinxinghui.model.account.RechargeSuccessActivity;
import com.sunday.pinxinghui.model.mine.SetPayPwdActivity;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.widgets.PayEdit;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.R.attr.order;

/**
 * Created by 刘涛 on 2017/8/20.
 */

public class OrderPayActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.total_money)
    TextView totalMoney;
    @Bind(R.id.select_pay_way)
    TextView selectPayWay;
    @Bind(R.id.balance_pay)
    CheckBox balancePay;
    @Bind(R.id.wechat_pay)
    CheckBox wechatPay;
    @Bind(R.id.alipay)
    CheckBox alipay;
    @Bind(R.id.btn_pay)
    Button btnPay;


    private long orderId;
    private String totalFee;
    private int payType = 1;
    private IWXAPI api;
    private String recieveName,recieveAddr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_pay);
        ButterKnife.bind(this);
        orderId = getIntent().getLongExtra("orderId", 0);
        totalFee = getIntent().getStringExtra("totalMoney");
        recieveName=getIntent().getStringExtra("recieveName");
        recieveAddr=getIntent().getStringExtra("recieveAddr");
        titleView.setText("确认支付");
        totalMoney.setText("¥" + totalFee);
        balancePay.setChecked(true);

        CheckChangedListener checkChangedListener = new CheckChangedListener();
        alipay.setOnCheckedChangeListener(checkChangedListener);
        wechatPay.setOnCheckedChangeListener(checkChangedListener);
        balancePay.setOnCheckedChangeListener(checkChangedListener);
        api = WXAPIFactory.createWXAPI(this, Constant.APP_ID);
        api.registerApp(Constant.APP_ID);
    }

    private class CheckChangedListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                alipay.setChecked(false);
                wechatPay.setChecked(false);
                balancePay.setChecked(false);
                switch (buttonView.getId()) {
                    case R.id.wechat_pay:
                        wechatPay.setChecked(true);
                        payType = 2;
                        break;
                    case R.id.alipay:
                        alipay.setChecked(true);
                        payType = 3;
                        break;
                    case R.id.balance_pay:
                        balancePay.setChecked(true);
                        payType = 1;
                        break;
                }
            } else {
                payType = 0;
            }
        }
    }

    @OnClick({R.id.left_btn, R.id.btn_pay})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_btn:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("温馨提示");
                builder.setMessage("订单会保留15分钟,请尽快支付");
                builder.setNegativeButton("确认离开", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        intent = new Intent(mContext, OrderListActivity.class);
                        startActivity(intent);
                        dialog.dismiss();
                        finish();
                    }
                });
                builder.setPositiveButton("继续支付", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();

                break;
            case R.id.btn_pay:
                if (payType == 0) {
                    ToastUtils.showToast(mContext, "请选择支付类型");
                    return;
                }
                if (new BigDecimal(totalFee).compareTo(BigDecimal.ZERO)<=0){
                    ToastUtils.showToast(mContext,"订单有误！请重新下单！");
                    return;
                }
                if (payType == 1) {
                    getBalance();
                } else {
                    getPayInfo();
                }
                break;
        }
    }

    Member member;

    private void getBalance() {
        Call<ResultDO<Member>> call = ApiClient.getApiAdapter().getMember(BaseApplication.getInstance().getMember().getId());
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    member = response.body().getResult();
                    if (new BigDecimal(totalFee).compareTo(BigDecimal.ZERO)<=0){
                        return;
                    }
                    if (member.getAmount().compareTo(new BigDecimal(totalFee)) < 0) {
                        showRechargeDialog();
                    } else if (member.getIsSetPayPwd()==0){
                        showSettingDialog();
                    }else if (member.getIsSetPayPwd()==1){
                        showPwdDialog();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {

            }
        });

    }

    private void showRechargeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(String.format("账户余额不足(剩余%s元)", member.getAmount().setScale(2, RoundingMode.HALF_UP)));
        builder.setMessage("请更换其他支付方式");
        builder.setNegativeButton("更换", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("充值", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                intent = new Intent(mContext, RechargeActivity.class);
                startActivity(intent);
            }
        });
        builder.show();
    }

    private String payPwd = null;

    private void showPwdDialog() {
        final AlertDialog myDialog = new AlertDialog.Builder(mContext).create();
        myDialog.setView(((Activity) mContext).getLayoutInflater().inflate(R.layout.pop_pay, null));
        myDialog.show();
        myDialog.getWindow().setContentView(R.layout.pop_pay);
        myDialog.getWindow().setGravity(Gravity.CENTER);
        TextView money = (TextView) myDialog.getWindow().findViewById(R.id.money);
        ImageView dismiss = (ImageView) myDialog.getWindow().findViewById(R.id.dismiss);
        final PayEdit edtPassword = (PayEdit) myDialog.getWindow().findViewById(R.id.edt_password);
        final InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edtPassword, InputMethodManager.SHOW_IMPLICIT);
        money.setText(String.valueOf(member.getAmount().setScale(2, RoundingMode.HALF_UP)));
        edtPassword.setOnTextEndListener(new PayEdit.OnTextEndListener() {
            @Override
            public void onTextEnd(String str) {
                payPwd = str;
                imm.hideSoftInputFromWindow(edtPassword.getWindowToken(), 0);
                myDialog.dismiss();
                getPayInfo();
            }
        });
        dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imm.hideSoftInputFromWindow(edtPassword.getWindowToken(), 0);
                myDialog.dismiss();
            }
        });
    }

    private PrePay payInfo;

    private void getPayInfo() {
        showLoadingDialog(0);
        Call<ResultDO<PrePay>> call = ApiClient.getApiAdapter().getPayInfo(orderId, payType, payPwd);
        call.enqueue(new Callback<ResultDO<PrePay>>() {
            @Override
            public void onResponse(Call<ResultDO<PrePay>> call, Response<ResultDO<PrePay>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    payInfo = response.body().getResult();
                    switch (payType) {
                        case 1:
                            ToastUtils.showToast(mContext, "支付成功");
                            intent=new Intent(mContext,PaySuccessActivity.class);
                            intent.putExtra("money",totalFee);
                            intent.putExtra("recieveName",recieveName);
                            intent.putExtra("recieveAddr",recieveAddr);
                            startActivity(intent);
                            finish();
                            break;
                        case 2:
                            wechatPay();
                            break;
                        case 3:
                            alipay();
                            break;
                        default:
                            ToastUtils.showToast(mContext,"请选择支付方式");
                            break;
                    }
                } else if (response.body().getCode() == 1) {
                    //支付密码错误
                    showReSettingDialog();
                } else if (response.body().getCode() == 2) {
                    //余额不足
                    showRechargeDialog();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }

            }

            @Override
            public void onFailure(Call<ResultDO<PrePay>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }
    private final static int REQUEST_PWD = 0x1113;
    private void showSettingDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("温馨提示");
        builder.setMessage("暂未设置交易密码");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                intent = new Intent(mContext, SetPayPwdActivity.class);
                intent.putExtra("fromPay", true);
                intent.putExtra("updateType",2);
                startActivityForResult(intent, REQUEST_PWD);
            }
        });
        builder.show();
    }

    private void showReSettingDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("密码不对");
        builder.setMessage("去修改交易密码");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                intent = new Intent(mContext, SetPayPwdActivity.class);
                intent.putExtra("fromPay", true);
                intent.putExtra("updateType",2);
                startActivityForResult(intent, REQUEST_PWD);
            }
        });
        builder.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_PWD:
                showPwdDialog();
                break;
        }
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    private void alipay() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(OrderPayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo.getAlipayString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    //Log.e("支付宝信息",payResult.toString());
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(mContext, "支付成功",
                                Toast.LENGTH_SHORT).show();
                        intent=new Intent(mContext,PaySuccessActivity.class);
                        intent.putExtra("money",totalFee);
                        intent.putExtra("recieveName",recieveName);
                        intent.putExtra("recieveAddr",recieveAddr);
                        startActivity(intent);
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(mContext, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

    };


    private void wechatPay() {
        PayReq req = new PayReq();
        req.appId = payInfo.getAppId();
        req.partnerId = Constant.PARTER_ID;
        req.prepayId = payInfo.getPrepayId();
        req.nonceStr = payInfo.getNonceStr();
        req.timeStamp = payInfo.getTimeStamp();
        req.packageValue = "Sign=WXPay";
        req.sign = payInfo.getPaySign();
        req.extData = "app data";
        api.sendReq(req);
    }


}
